package com.ruoyi.web.controller.attach;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.QiniuImageUploader;
import com.ruoyi.file.service.IFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private IFileService biz;

//    @Autowired
//    private ICommonAttachService attachBiz;
//
//    @Autowired
//    private ISysUserService userService;

    @Value("${upload.domainOfBucketCommon}")
    String domain_common;
    @Value("${upload.bucketCommon}")
    String bucket_common;
    @Value("${upload.domainOfBucket}")
    String domain;
    @Value("${upload.bucket}")
    String bucket;

    @GetMapping("/upload/token")
    public R<Map> getUpToken(String bucket, String domain){
        if(StringUtils.isEmpty(bucket)) {
            bucket = this.bucket;
        }
        if(StringUtils.isEmpty(domain)) {
            domain = this.domain;
        }
        String token = biz.getUpToken(bucket, 60*60*12);
        Map<String, String> res = new HashMap<>();
        res.put("token", token);
        res.put("key", StringUtils.getUUID());
        res.put("domain", domain);
        res.put("bucket", bucket);
        return R.data(res);
    }

    @GetMapping("/upload/token/common")
    public R<Map> getCommonUpToken(){
        return getUpToken(bucket_common, domain_common);
    }

    @RequestMapping(value="/downloadFile")
    public void downloadFile(String key, HttpServletResponse response) throws IOException {
        response.sendRedirect(QiniuImageUploader.getUrl(key, bucket_common));
    }

    @RequestMapping(value="/downloadCommonFile")
    public void downloadCommonFile(String key, HttpServletResponse response) throws IOException {
        response.sendRedirect(QiniuImageUploader.getUrl(key, bucket_common));
    }

//    @RequestMapping(value="/deleteCommonFile")
//    public ModelAndView deleteCommon(String key){
//        ModelAndView mv = new ModelAndView(new MappingJackson2JsonView());
//        try {
//            attachBiz.deleteByFkey(key);
//            biz.delete(key, bucket_common);
//            return mv.addObject("success", true);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return mv.addObject("success", false).addObject("message", e.getMessage());
//        }
//    }

    @RequestMapping(value = "/image/upload", method = RequestMethod.POST)
    public R upload(@RequestParam CommonsMultipartFile imgFile) {
        String fileName = "xbky/img/"+new SimpleDateFormat("yyyy-MM-dd/").format(new Date())+ StringUtils.getUUID()+"/"+imgFile.getOriginalFilename().replace(" ", "");
        QiniuImageUploader.MyRet ret = QiniuImageUploader.upload(imgFile.getBytes(), fileName);
        if (ret == null)
            return R.fail();
        return R.data(QiniuImageUploader.getUrl(ret.key, bucket_common));
    }

    @PostMapping(value = "/upload")
//    @SystemControllerLog(description = "附件上传")
    public R upload(@RequestParam MultipartFile file, String type, String relId,
                    HttpServletRequest request) throws IOException {
        Map<String, Object> data = new HashMap<String, Object>();
        String fileName = "xbky/" + type + "/" + new SimpleDateFormat("yyyy-MM-dd/").format(new Date())
                + StringUtils.getUUID() + "/" + file.getOriginalFilename().trim();
        QiniuImageUploader.MyRet ret = QiniuImageUploader.upload(file.getBytes(), fileName);
        if (ret == null)
            return R.fail();
        // 保存附件信息
        //data.put("previewImage", biz.buildPreviewImage(ret, file));
//        data.put("id", saveAtt(file.getOriginalFilename(), ret, type, relId));
        data.put("url", QiniuImageUploader.getUrl(ret.key, bucket_common));
        data.put("name", file.getOriginalFilename().trim());
        return R.data(data);
    }

//    @SystemControllerLog(description = "附件上传-保存记录")
    @PostMapping("/upload/save")
    public R upload(@RequestBody Map<String, Object> params){
        if(params.isEmpty() && !params.containsKey("key")) {
            return R.fail("参数异常");
        }
        Map<String, Object> data = new HashMap();
//        data.put("id", saveAtt(params));
        data.put("url", QiniuImageUploader.getUrlByPriv(params.get("key").toString(), params.get("bucket").toString()));
        return R.data(data);
    }

    /**
     * CKeditor编辑器图片上传
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/ck/image/upload", method = RequestMethod.POST)
    public Map<String, Object> ckImgUpload(@RequestParam MultipartFile upload, HttpServletRequest request) throws IOException {
        Map<String, Object> result = new HashMap<String, Object>();
        String fileName = "xbky/img/"+new SimpleDateFormat("yyyy-MM-dd/").format(new Date())+ StringUtils.getUUID()+"/"+upload.getOriginalFilename().replace(" ", "");
        QiniuImageUploader.MyRet ret= QiniuImageUploader.upload(upload.getBytes(), fileName);
        if(ret != null) {
            result.put("uploaded", true);
            result.put("url", ret.url);
        }else {
            result.put("uploaded", false);
        }
        return result;
    }

    /**
     * 保存附件信息
     *
     * @param fileName
     *            文件名
     * @param ret
     *            七牛返回数据包装对象
     * @param type
     *            附件类型
     * @return 附件id
     */
//    private String saveAtt(String fileName, MyRet ret, String type, String relId) {
//        CommonAttach t = new CommonAttach();
//        t.setId(StringUtils.getUUID());
//        t.setLrr(getLoginUserName());
//        t.setLrsj(DateUtils.getCurrentDate());
//        t.setGxr(getLoginUserName());
//        t.setLastModifiedDate(DateUtils.getCurrentDate());
//        t.setIsDel("0");
//        t.setName(fileName);
//        t.setBucket(ret.bucket);
//        t.setDescription(type);
//        t.setRelId(relId);
//        if (StringUtils.isNotEmpty(ret.ext))
//            t.setExt(ret.ext.substring(1, ret.ext.length()));
//        t.setFkey(ret.key);
//        t.setHash(ret.hash);
//        t.setOrigSize(Double.valueOf(ret.fsize));
//        t.setSize(Double.valueOf(ret.fsize));
//        t.setType(ret.mimeType);
//        t.setIsImage(ret.ext);
//        if (ret.previewImage != null) {
//            t.setPreviewImage(ret.previewImage.getBytes());
//        }
//        int result = attachBiz.save(t);
//        if (result == 1) {
//            return t.getId();
//        }
//        return null;
//    }

//    private String saveAtt(Map<String, Object> params) {
//        CommonAttach t = new CommonAttach();
//        t.setId(StringUtils.getUUID());
//        t.setLrr(getLoginUserName());
//        t.setLrsj(DateUtils.getCurrentDate());
//        t.setGxr(getLoginUserName());
//        t.setLastModifiedDate(DateUtils.getCurrentDate());
//        t.setIsDel("0");
//        t.setName(params.get("fileName").toString());
//        t.setBucket(params.get("bucket").toString());
//        t.setType("attach");
//        t.setFkey(params.get("key").toString());
//        t.setHash(params.get("hash").toString());
//        if(StringUtils.contains(t.getFkey(), ".")) {
//            t.setExt(t.getFkey().substring(t.getFkey().lastIndexOf(".") + 1));
//        }
//        t.setExt(String.valueOf(params.getOrDefault("ext", "")));
//        t.setDescription(String.valueOf(params.getOrDefault("description", "")));
//        t.setOrigSize(Double.valueOf(params.get("fsize").toString()));
//        t.setSize(Double.valueOf(params.get("fsize").toString()));
//        int result = attachBiz.save(t);
//        if (result == 1) {
//            return t.getId();
//        }
//        return null;
//    }
}
